package core;

import com.sun.lwuit.Font;
import java.util.Vector;
import javax.microedition.rms.*;
import view.FunctionMenu;
import view.ViewManager;
import view.additional.CellItem;

public class PositionManager
{
	private Vector positions;
	private String rmsName;
	private long lastChange;
        private int UIDInf;
	
	public PositionManager()
	{
		positions = new Vector();
		rmsName = "positionsDB";
		lastChange = 0;
                UIDInf = -1;
		load();
	}
	
	private void load()
	{
		clear();
		try
		{
			RecordStore recordStore = RecordStore.openRecordStore(rmsName, true);
			RecordEnumeration re = recordStore.enumerateRecords(null, null, false);
			if (re.numRecords()!=0)
			{
				re.rebuild();
				while (re.hasNextElement())
				{
					int id = re.nextRecordId();
					try
					{
						positions.insertElementAt((new Position(recordStore.getRecord(id))),0);
					}catch(Exception e){}
				}
			}
			recordStore.closeRecordStore();
			re.destroy();
		}catch(RecordStoreException rse){}
	}
	
	public void save()
	{
		//������� ��� ������,���� �� ����������� ������
		try
		{
			RecordStore.deleteRecordStore(rmsName);
		}catch(Exception e){}
		//��������� ������
		byte[] res;
		try
		{
			RecordStore recordStore = RecordStore.openRecordStore(rmsName, true);
			for(int i=0;i<positions.size();i++)
			{
				res = ((Position)positions.elementAt(i)).toByte();
				recordStore.addRecord(res,0,res.length);
			}
			recordStore.closeRecordStore();
		}catch(RecordStoreException rse){}
	}

        public void clearUIDInf()
        {
            this.UIDInf = -1;
        }

        public void setUIDInf(int UIDInf)
        {
            this.UIDInf = UIDInf;
        }

	public void clear()
	{
		positions.removeAllElements();
	}

        public void addPosition(Position value)
        {
            positions.addElement(value);
        }
	
	public void setLastChange(long newDate)
	{
		lastChange = newDate;
	}
	
	public long getLastChange()
	{
		return lastChange;
	}
	
	public String[] getRegions()
	{
		Vector temp;
		String[] res;
		temp = new Vector();
		
		for (int i=0;i<positions.size();i++)
		{
			if (!inVector(temp,((Position)positions.elementAt(i)).getParkingRegion()))
			{
				temp.addElement(((Position)positions.elementAt(i)).getParkingRegion());
			}
		}
		
		res = new String[temp.size()];
		for (int i=0;i<temp.size();i++)
		{
			res[i] = ((String)temp.elementAt(i));
		}
		return res;
	}

        public CellItem[] getParkingForStatistic(String currRegion)
	{
            Vector temp;
            CellItem[] res;
            temp = new Vector();
            String s;
            boolean isChernovtsi = (ViewManager.getViewManager().getFunctionMenuType() == FunctionMenu.CHERNOVTSI_TYPE);

            for (int i=0;i<positions.size();i++)
            {
                    if (currRegion.equals(((Position)positions.elementAt(i)).getParkingRegion()))
                    {
                        if (isChernovtsi)
                        {
                            s = ((Position)positions.elementAt(i)).getParkingName();
                            CellItem itm = new CellItem(((Position)positions.elementAt(i)).getId(),s);

                            if (itm.getId() == UIDInf)
                            {
                                itm.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED | Font.STYLE_BOLD
                                                                             , Font.SIZE_MEDIUM));
                                itm.getSelectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED | Font.STYLE_BOLD
                                                                , Font.SIZE_MEDIUM));
                            }
                            temp.addElement(itm);
                        }
                        else
                        {
                            s = ((Position)positions.elementAt(i)).getParkingName() + " (" + ((Position)positions.elementAt(i)).getCarsCount() + "):" +((Position)positions.elementAt(i)).getQueue()+"\n";
                            temp.addElement(new CellItem(((Position)positions.elementAt(i)).getId(),s));
                        }      
                    }
            }

            res = new CellItem[temp.size()];
            for (int i=0;i<temp.size();i++)
            {
                    res[i] = ((CellItem)temp.elementAt(i));
            }
            return res;
	}

	public CellItem[] getParking(String currRegion)
	{
		Vector temp;
		CellItem[] res;
		temp = new Vector();
		String s;
                
		for (int i=0;i<positions.size();i++)
		{
			if (currRegion.equals(((Position)positions.elementAt(i)).getParkingRegion()))
			{
                            s = ((Position)positions.elementAt(i)).getParkingName() + "(" +((Position)positions.elementAt(i)).getCarsCount()+")\n";
                            temp.addElement(new CellItem(((Position)positions.elementAt(i)).getId(),s));
			}
		}
		
		res = new CellItem[temp.size()];
		for (int i=0;i<temp.size();i++)
		{
			res[i] = ((CellItem)temp.elementAt(i));
		}
		return res;
	}

        public String[] getAllParkingsForStatistic()
        {
            String[] res;
            res = new String[positions.size()+1];
            //Этот элемент заполнит визуалка инфой о водителе
            res[0] = "";
            for (int i=0;i<positions.size();i++)
            {
                res[i+1] = (((Position)positions.elementAt(i)).getParkingName()) + ":";
                res[i+1] += ((Position)positions.elementAt(i)).getQueue();
            }
            return res;
        }

	public String[] getAllParkings()
	{
		String[] res;
		res = new String[positions.size()];
		for (int i=0;i<positions.size();i++)
		{
			res[i] = (((Position)positions.elementAt(i)).getParkingName()) + "(";
                        res[i] += ((Position)positions.elementAt(i)).getCarsCount()+")";
		}
		return res;
	}
	
	public int getIdByNames(String region,String name)
	{
            Position currentPos;
            for (int i=0;i<positions.size();i++)
            {
                currentPos = (Position)positions.elementAt(i);
                if (name.equals(currentPos.getParkingName()) && (region.equals(currentPos.getParkingRegion())))
                {
                    return currentPos.getId();
		}
            }

            //Ничего не нашли
            return -1;
	}

        public int getIdByNumber(int number)
        {
            try
            {
                return ((Position)positions.elementAt(number)).getId();
            }catch(Exception e){return -1;}
        }

        public String getRegionByPositionID(int id)
        {
            for (int i=0;i<positions.size();i++)
		{
			if (((Position)positions.elementAt(i)).getId()==id)
			{
				return ((Position)positions.elementAt(i)).getParkingRegion();
			}
		}
		return "";
        }

	public String getNameByID(int id)
	{
		for (int i=0;i<positions.size();i++)
		{
			if (((Position)positions.elementAt(i)).getId()==id)
			{
				return ((Position)positions.elementAt(i)).getParkingName();
			}
		}
		return "не определен";
	}
	
	private boolean inVector(Vector param,String value)
	{
		for (int i=0;i<param.size();i++)
		{
			if (value.equals((String)param.elementAt(i)))
			{
				return true;
			}
		}
		return false;
	}

        public void updateCarsCount(Vector params)
        {
            //Обнуляем значения стоянок
            for (int i=0;i<positions.size();i++)
            {
                ((Position)positions.elementAt(i)).setCarsCount(0);
                ((Position)positions.elementAt(i)).setQueue("");
            }

            //Изменяем значения кол-ва машин по стоянкам
            Statistic statistic;
            for (int i = 0; i < params.size(); ++i)
            {
                statistic = (Statistic)params.elementAt(i);
                //Изменяем значение кол-ва машин по стоянкам
                for (int j=0;j<positions.size();j++)
                    if (((Position)positions.elementAt(j)).getId() == statistic.getId())
                    {
                        ((Position)positions.elementAt(j)).setCarsCount(statistic.getCount());
                        ((Position)positions.elementAt(j)).setQueue(statistic.getQueue());
                        break;
                    }
            }
        }

        public String getCarsCount(int parkingID)
        {
            for (int i=0;i<positions.size();i++)
            {
                if (((Position)positions.elementAt(i)).getId()==parkingID)
                {
                    return ((Position)positions.elementAt(i)).getCarsCount();
                }
            }
            return "0";
        }
}
